/**
 * 项目管理前端脚本
 */

class ProjectManager {
    constructor() {
        this.baseURL = 'http://localhost:8080';
        this.token = this.getToken();
        this.projects = [];
        this.users = [];
        this.currentProject = null;
        this.isEditing = false;
    }

    /**
     * 获取JWT令牌
     */
    getToken() {
        return localStorage.getItem('token') || sessionStorage.getItem('token');
    }

    /**
     * 通用API请求方法
     */
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.token}`,
                ...options.headers
            },
            ...options
        };

        try {
            const response = await fetch(url, config);
            
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    /**
     * 获取所有项目
     */
    async loadProjects() {
        try {
            this.showLoading();
            this.projects = await this.request('/projects');
            this.renderProjects();
        } catch (error) {
            this.showError('加载项目列表失败: ' + error.message);
        }
    }

    /**
     * 获取所有用户（用于负责人选择）
     */
    async loadUsers() {
        try {
            this.users = await this.request('/users');
            this.renderUserOptions();
        } catch (error) {
            console.error('加载用户列表失败:', error);
        }
    }

    /**
     * 创建项目
     */
    async createProject(projectData) {
        try {
            const newProject = await this.request('/projects', {
                method: 'POST',
                body: JSON.stringify(projectData)
            });
            
            this.projects.push(newProject);
            this.renderProjects();
            this.closeModal();
            this.showSuccess('项目创建成功！');
        } catch (error) {
            this.showModalError('创建项目失败: ' + error.message);
        }
    }

    /**
     * 更新项目
     */
    async updateProject(id, projectData) {
        try {
            const updatedProject = await this.request(`/projects/${id}`, {
                method: 'PUT',
                body: JSON.stringify(projectData)
            });
            
            const index = this.projects.findIndex(p => p.id === id);
            if (index !== -1) {
                this.projects[index] = updatedProject;
            }
            
            this.renderProjects();
            this.closeModal();
            this.showSuccess('项目更新成功！');
        } catch (error) {
            this.showModalError('更新项目失败: ' + error.message);
        }
    }

    /**
     * 删除项目
     */
    async deleteProject(id) {
        if (!confirm('确定要删除这个项目吗？此操作不可撤销。')) {
            return;
        }

        try {
            await this.request(`/projects/${id}`, {
                method: 'DELETE'
            });
            
            this.projects = this.projects.filter(p => p.id !== id);
            this.renderProjects();
            this.showSuccess('项目删除成功！');
        } catch (error) {
            this.showError('删除项目失败: ' + error.message);
        }
    }

    /**
     * 渲染项目列表
     */
    renderProjects(projectsToRender = this.projects) {
        const tbody = document.getElementById('projectsTableBody');
        
        if (projectsToRender.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="empty-state">
                        <h3>暂无项目</h3>
                        <p>点击"新建项目"按钮创建第一个项目</p>
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = projectsToRender.map(project => `
            <tr>
                <td>${project.projectName || '-'}</td>
                <td>${project.projectCode || '-'}</td>
                <td>${project.principalInvestigatorName || '未分配'}</td>
                <td>
                    <span class="status-badge ${this.getStatusClass(project.status)}">
                        ${this.getStatusText(project.status)}
                    </span>
                </td>
                <td>${project.startDate || '-'}</td>
                <td>${project.endDate || '-'}</td>
                <td>${project.budgetAmount ? '¥' + Number(project.budgetAmount).toLocaleString() : '-'}</td>
                <td>
                    <div class="actions">
                        <button class="btn btn-primary btn-sm" onclick="projectManager.viewProject(${project.id})">
                            👁️ 查看
                        </button>
                        <button class="btn btn-warning btn-sm" onclick="projectManager.editProject(${project.id})">
                            ✏️ 编辑
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="projectManager.deleteProject(${project.id})">
                            🗑️ 删除
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }

    /**
     * 渲染用户选项
     */
    renderUserOptions() {
        const select = document.getElementById('principalInvestigatorId');
        select.innerHTML = '<option value="">请选择负责人</option>' + 
            this.users.map(user => `
                <option value="${user.id}">${user.fullName || user.username} (${user.department || '未知部门'})</option>
            `).join('');
    }

    /**
     * 获取状态样式类
     */
    getStatusClass(status) {
        const statusMap = {
            'PENDING_APPROVAL': 'status-pending',
            'IN_PROGRESS': 'status-in-progress',
            'COMPLETED': 'status-completed',
            'ON_HOLD': 'status-on-hold',
            'REJECTED': 'status-rejected'
        };
        return statusMap[status] || 'status-pending';
    }

    /**
     * 获取状态显示文本
     */
    getStatusText(status) {
        const statusMap = {
            'PENDING_APPROVAL': '待审批',
            'IN_PROGRESS': '进行中',
            'COMPLETED': '已完成',
            'ON_HOLD': '暂停中',
            'REJECTED': '已拒绝'
        };
        return statusMap[status] || status;
    }

    /**
     * 显示创建项目模态框
     */
    showCreateModal() {
        this.isEditing = false;
        this.currentProject = null;
        
        document.getElementById('modalTitle').textContent = '新建项目';
        document.getElementById('projectForm').reset();
        document.getElementById('modalError').style.display = 'none';
        
        // 加载用户列表
        this.loadUsers();
        
        document.getElementById('projectModal').style.display = 'block';
    }

    /**
     * 查看项目详情
     */
    async viewProject(id) {
        try {
            const project = await this.request(`/projects/${id}`);
            this.showProjectDetails(project, true); // 只读模式
        } catch (error) {
            this.showError('获取项目详情失败: ' + error.message);
        }
    }

    /**
     * 编辑项目
     */
    async editProject(id) {
        try {
            const project = await this.request(`/projects/${id}`);
            this.showProjectDetails(project, false); // 编辑模式
        } catch (error) {
            this.showError('获取项目详情失败: ' + error.message);
        }
    }

    /**
     * 显示项目详情
     */
    showProjectDetails(project, readOnly = false) {
        this.isEditing = !readOnly;
        this.currentProject = project;
        
        document.getElementById('modalTitle').textContent = readOnly ? '项目详情' : '编辑项目';
        document.getElementById('modalError').style.display = 'none';
        
        // 填充表单数据
        document.getElementById('projectName').value = project.projectName || '';
        document.getElementById('projectCode').value = project.projectCode || '';
        document.getElementById('description').value = project.description || '';
        document.getElementById('startDate').value = project.startDate || '';
        document.getElementById('endDate').value = project.endDate || '';
        document.getElementById('status').value = project.status || 'PENDING_APPROVAL';
        document.getElementById('budgetAmount').value = project.budgetAmount || '';
        
        // 加载用户列表并设置当前负责人
        this.loadUsers().then(() => {
            // 根据负责人姓名找到对应的用户ID
            const piUser = this.users.find(user => user.fullName === project.principalInvestigatorName);
            if (piUser) {
                document.getElementById('principalInvestigatorId').value = piUser.id;
            }
        });
        
        // 设置表单只读状态
        const formElements = document.querySelectorAll('#projectForm input, #projectForm select, #projectForm textarea');
        formElements.forEach(element => {
            element.disabled = readOnly;
        });
        
        // 更新保存按钮
        const saveButton = document.querySelector('.modal-footer .btn-success');
        if (readOnly) {
            saveButton.style.display = 'none';
        } else {
            saveButton.style.display = 'inline-block';
            saveButton.textContent = '更新';
        }
        
        document.getElementById('projectModal').style.display = 'block';
    }

    /**
     * 保存项目
     */
    async saveProject() {
        const form = document.getElementById('projectForm');
        const formData = new FormData(form);
        
        const projectData = {
            projectName: formData.get('projectName'),
            projectCode: formData.get('projectCode'),
            description: formData.get('description'),
            startDate: formData.get('startDate') || null,
            endDate: formData.get('endDate') || null,
            status: formData.get('status'),
            budgetAmount: formData.get('budgetAmount') ? parseFloat(formData.get('budgetAmount')) : null,
            principalInvestigatorId: parseInt(formData.get('principalInvestigatorId'))
        };

        // 验证必填字段
        if (!projectData.projectName || !projectData.status || !projectData.principalInvestigatorId) {
            this.showModalError('请填写所有必填字段');
            return;
        }

        if (this.isEditing && this.currentProject) {
            await this.updateProject(this.currentProject.id, projectData);
        } else {
            await this.createProject(projectData);
        }
    }

    /**
     * 关闭模态框
     */
    closeModal() {
        document.getElementById('projectModal').style.display = 'none';
        document.getElementById('projectForm').reset();
        document.getElementById('modalError').style.display = 'none';
        
        // 恢复表单可编辑状态
        const formElements = document.querySelectorAll('#projectForm input, #projectForm select, #projectForm textarea');
        formElements.forEach(element => {
            element.disabled = false;
        });
        
        // 恢复保存按钮
        const saveButton = document.querySelector('.modal-footer .btn-success');
        saveButton.style.display = 'inline-block';
        saveButton.textContent = '保存';
    }

    /**
     * 搜索项目
     */
    searchProjects() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();
        
        if (!searchTerm) {
            this.renderProjects();
            return;
        }

        const filteredProjects = this.projects.filter(project => 
            (project.projectName && project.projectName.toLowerCase().includes(searchTerm)) ||
            (project.projectCode && project.projectCode.toLowerCase().includes(searchTerm)) ||
            (project.principalInvestigatorName && project.principalInvestigatorName.toLowerCase().includes(searchTerm))
        );

        this.renderProjects(filteredProjects);
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const tbody = document.getElementById('projectsTableBody');
        tbody.innerHTML = '<tr><td colspan="8" class="loading">加载中...</td></tr>';
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const tbody = document.getElementById('projectsTableBody');
        tbody.innerHTML = `<tr><td colspan="8" class="error">❌ ${message}</td></tr>`;
    }

    /**
     * 显示模态框错误信息
     */
    showModalError(message) {
        const errorDiv = document.getElementById('modalError');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    /**
     * 显示成功信息
     */
    showSuccess(message) {
        // 创建临时成功提示
        const successDiv = document.createElement('div');
        successDiv.className = 'success';
        successDiv.textContent = '✅ ' + message;
        successDiv.style.position = 'fixed';
        successDiv.style.top = '20px';
        successDiv.style.right = '20px';
        successDiv.style.zIndex = '9999';
        successDiv.style.padding = '15px 20px';
        successDiv.style.borderRadius = '4px';
        successDiv.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        
        document.body.appendChild(successDiv);
        
        setTimeout(() => {
            document.body.removeChild(successDiv);
        }, 3000);
    }

    /**
     * 初始化
     */
    init() {
        // 检查登录状态
        if (!this.token) {
            alert('请先登录');
            window.location.href = '/login.html';
            return;
        }

        // 加载项目列表
        this.loadProjects();

        // 绑定搜索框回车事件
        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchProjects();
            }
        });

        // 绑定模态框点击外部关闭事件
        document.getElementById('projectModal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('projectModal')) {
                this.closeModal();
            }
        });
    }
}

// 全局函数
function showCreateModal() {
    projectManager.showCreateModal();
}

function closeModal() {
    projectManager.closeModal();
}

function saveProject() {
    projectManager.saveProject();
}

function loadProjects() {
    projectManager.loadProjects();
}

function searchProjects() {
    projectManager.searchProjects();
}

// 创建全局实例
const projectManager = new ProjectManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    projectManager.init();
});
